// pages/tiku/kaoti_timu.js1
//获取应用实例
const app = getApp()
//定时
//var Interval = '';
//考试开始时间
var starttime = '';
//考试结束时间
//以下数据用于关闭页面
var is_play = 1;
var onUnload_TaskId = '';
var onUnload_id = '';
var onUnload_isEnd = '';
var onUnload_sort = '';
//用于管理员权限
var video_admin = null;//管理员权限
//身份验证标志
var isIdentityCheck = 0;//身份验证标志 默认不开启
//视频时长
var videoDuration = 0;
var learn_video_id = '';
var learn_video_task_id = '';


//身份验证时间
var identityCheckTime1 = -1;
var identityCheckTime2 = -1;
var identityCheckTime3 = -1;
var identityCheckTime4 = -1;
var identityCheckTime5 = -1;
var identityCheckTime6 = -1;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        video_item: {},
        video_real_time:0, //实时播放进度
        initial_time:0, //视频跳转进度 秒
        windowHeight: 0,
        play_flag: '',
        completed: false,  // 弹窗控制
        deposit: 0 , // 存储用户输入的内容
        identityCheckTime:-1,//默认身份验证时间
        identityCheckContent: '', //身份校验用户填写内容
        employeeName: '' //用户姓名
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      try {
        var empinfo = wx.getStorageSync('empinfo');
        var isIdentityCheck1 = wx.getStorageSync('isIdentityCheck');
        //console.log('身份校验开关为1：'+isIdentityCheck1)
        //身份验证开关赋值
        if(isIdentityCheck1){
          isIdentityCheck = isIdentityCheck1;
        }
        if (empinfo) {
          var that = this;
          starttime = '';
          is_play = '';
          //学习视频记录子表ID
        var video_record_item_id = options.id;
        that.setData({
            initial_time:0, //视频进度
            employeeName:empinfo.employeeName,//用户姓名
          });
          //管理员权限赋值
          video_admin = empinfo.adminMobile;
          if(null == video_record_item_id || "" == video_record_item_id){
            wx.showToast({
                title: '未获取到视频数据，请稍后再试！',
                icon: 'none',
                duration: 2000
              })
          }else{
              //获取视频数据
              app.formPost('/wx/video/get_video_item', {
                  'video_record_item_id': video_record_item_id
              }).then(res => {
                  if (res.code == 200) {
                      that.setData({
                          video_item: res.video_item
                      })
                      var is_End = res.video_item.isEnd;
                      videoDuration = res.video_item.videoDuration;
                      learn_video_id = res.video_item.learnVideoId;
                      learn_video_task_id = res.video_item.learnVideoTaskId;
                      if(isIdentityCheck != 0){
                        this.identityCheckTime(videoDuration);
                      }
                      if(is_End == 0){
                        //上次播放位置
                          var last_time_duration = res.video_item.lastTimeDuration;
                          var last_time_duration_show = res.video_item.lastTimeDurationShow;
                          console.log('上次学习时间为'+last_time_duration)
                          console.log('上次学习时间为'+last_time_duration_show)
                          if(last_time_duration > 0){
                            //console.log('上次播放位置不为空：' +last_time_duration_show)
                            wx.showModal({
                              content: '上次学习到'+last_time_duration_show+',是否继续？',
                              success(res) {
                                if (res.confirm) {
                                    //console.log('继续播放')
                                    that.setData({
                                      initial_time: last_time_duration
                                    })
                                    var videoCtx = wx.createVideoContext("myVideo", this);
                                    //videoCtx.play();
                                    videoCtx.seek(last_time_duration);
                                    videoCtx.play();
                                    //VideoContext.seek(number position)
                                    
                                } else if (res.cancel) {
                                  console.log('从头播放' )
                                }
                              }
                            })
                          }
                      }
                      
                  }
              }).catch(e => {
                  wx.showModal({
                  title: e
                  })
              })
          }
        }else{
          wx.reLaunch({
            url: '/pages/user/bind/index',
          });
        }
      } catch (e) {
        wx.reLaunch({
          url: '/pages/user/bind/index',
        });
      }
    },
    
    //监听视频播放进度
   timeUpdate: function (e) {
    var aa = 1; // 是否开启可以视频快进 1 禁止开启
    var id = e.currentTarget.id;
    var isEnd = e.currentTarget.dataset.item.isEnd;
   // console.log('admin===='+admin)
    if(isEnd == 1){
        aa = 0;
        isIdentityCheck = 0;
    }
    if(video_admin != null){
      aa = 0;
      isIdentityCheck = 0;
    }
    //跳转到指定播放位置 initial-time 时间为秒
    let that = this;
    //播放的总时长
    //var duration = e.detail.duration
    //实时播放进度 秒数
    var currentTime = parseInt(e.detail.currentTime)
    //console.log("实时播放进度秒数：" + currentTime + "秒")
    //当前视频进度 videoDuration
    //console.log('身份验证开关为'+isIdentityCheck)
    //console.log("视频播放到第" + currentTime + "秒")//查看正在播放时间，以秒为单位
    if (that.data.video_real_time==0){
      //console.log("播放位置" + that.data.initial_time + "秒")
      var jump_time = parseInt(that.data.initial_time) + parseInt(that.data.video_real_time)
    }else{
      var jump_time = parseInt(that.data.video_real_time)
    }
    if(aa==1){
      if (currentTime > jump_time && currentTime - jump_time>3){
        let videoContext = wx.createVideoContext(id)
        videoContext.seek(that.data.video_real_time)
        wx.showToast({
          title: '未完整看完该视频，不能快进',
          icon: 'none',
          duration: 3000,
        })
      }
    } 
    //console.log('身份验证标致为'+isIdentityCheck)
    if(isIdentityCheck == 1){
      if(currentTime == identityCheckTime1){
        //console.log('第1次身份验证')
        //currentTime = currentTime+1;
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime1
        })
       }else if(currentTime == identityCheckTime2){
        //currentTime = currentTime+1;
        //console.log('第2次身份验证')
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime2
        })
       }else if(currentTime == identityCheckTime3){
        //currentTime = currentTime+1;
        //console.log('第3次身份验证')
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime3
        })
       }else if(currentTime == identityCheckTime4){
        //currentTime = currentTime+1;
        //console.log('第4次身份验证')
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime4
        })
       }else if(currentTime == identityCheckTime5){
        //currentTime = currentTime+1;
        //console.log('第5次身份验证')
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime5
        })
      }else if(currentTime == identityCheckTime6){
        //currentTime = currentTime+1;
        //console.log('第6次身份验证')
        var videoCtx = wx.createVideoContext("myVideo", this);
        videoCtx.pause();
        that.setData({
          completed: true,
          identityCheckTime:identityCheckTime6
        })
      }
    }
    that.setData({
      video_real_time: currentTime, //实时播放进度
    })
  },
  
  //组件播放
  play: function (e){
    //let that = this;
    //starttime = '',
        // var onUnload_TaskId = ''; --
	      // var onUnload_id = '';--
	      // var onUnload_isEnd = '';
	      // var onUnload_sort = '';
    is_play = 1;
    starttime = Date.parse(new Date());
    //console.log('点击视频播记录时间:'+starttime)
    var isEnd = e.currentTarget.dataset.item.isEnd;
    onUnload_isEnd = isEnd;
    //console.log('isEnd==='+isEnd)
    //console.log('视频播放完毕时间:'+starttime)
    var id = e.currentTarget.dataset.item.id;
    onUnload_id = id;
    //console.log('id==='+id)
    var learnVideoTaskId = e.currentTarget.dataset.item.learnVideoTaskId;
    onUnload_TaskId = learnVideoTaskId;
    //console.log('learnVideoTaskId==='+learnVideoTaskId)
    var sort = e.currentTarget.dataset.item.sort;
    onUnload_sort = sort;
    //console.log('sort==='+sort)
    
    try {
      var empinfo = wx.getStorageSync('empinfo');
      if (empinfo) {
        if(sort==1){
          if(isEnd != 1){
            //console.log('第一个的第一次播放')
            //记录学习视频进度
              app.formPost('/wx/video/record_start_date', {
                'employeeId': empinfo.employeeId,
                'learnVideoTaskId': learnVideoTaskId,
                'id':id
            }).then(res => {
                if (res.code == 200) {
                  console.log('开始日期已经更新')
                }
            }).catch(e => {
                wx.showModal({
                title: e
                })
            })
          }
        }else{
          if(isEnd != 1){
            //console.log('不是第一个的第一次播放')
            //记录学习视频进度
              app.formPost('/wx/video/record_item_start_date', {
                'id':id
            }).then(res => {
                if (res.code == 200) {
                  console.log('开始日期已经更新')
                }
            }).catch(e => {
                wx.showModal({
                title: e
                })
            })
          }
        }
      }else{
        wx.reLaunch({
          url: '/pages/user/bind/index',
        });
      }
    } catch (e) {
      wx.reLaunch({
        url: '/pages/user/bind/index',
      });
    }
    
    //console.log('isEnd:'+isEnd)
    //用户信息
    
  },
   //播放按钮
   playVideo: function (event){
    var videoCtx = wx.createVideoContext("myVideo", this);
    videoCtx.play();
  },
  //暂停按钮
  pauseVideo: function (event){
    //console.log('暂停按钮点击一下')
     var videoCtx = wx.createVideoContext("myVideo", this);
     videoCtx.pause();
  },
  //完毕
  ended: function (e){
    //console.log('结束按钮被调用')
    //var that = this;
    is_play = 0;
    //console.log('视频完毕')
    var endtime = Date.parse(new Date());
    //console.log('视频完毕录时间:'+endtime)
    // 相差的毫秒数1
    const msec = endtime - starttime;
    const msec1 = msec/1000;
    //console.log('视频完毕时长msec1:'+msec1)
    //console.log('视频完毕播放进度:'+this.data.video_real_time)
    //console.log(e)
    //console.log('播放完毕时间====>' + this.data.video_real_time)
    var isEnd = e.currentTarget.dataset.item.isEnd;
    //console.log('isEnd==='+isEnd)
    //console.log('视频播放完毕时间:'+starttime)
    var id = e.currentTarget.dataset.item.id;
    var learnVideoTaskId = e.currentTarget.dataset.item.learnVideoTaskId;
    var sort = e.currentTarget.dataset.item.sort;
    //console.log('isEnd:'+isEnd)
    //用户信息
    
    try {
      var empinfo = wx.getStorageSync('empinfo');
      if (empinfo) {
        //console.log('进入播放完毕后台')
          app.formPost('/wx/video/video_ended', {
            'employeeId': empinfo.employeeId,
            'learnVideoTaskId': learnVideoTaskId,
            'id':id,
            'isEnd': isEnd,
            'playLength': msec1,
            'sort': sort
        }).then(res => {
            if (res.code == 200) {
                var next_id = res.next_id;
                if(next_id != null){
                  wx.showModal({
                    content: '确定进入下一个视频任务吗？',
                    success(res) {
                      if (res.confirm) {
                          wx.redirectTo({
                            url: '/pages/tiku/kaoti_timu?id=' + next_id,
                          })
                      } else if (res.cancel) {
                        wx.redirectTo({
                          url: '/pages/tiku/kaoti_timu?id=' + id,
                        })
                      }
                    }
                  })
                }else{
                  wx.showToast({
                    title: '恭喜您，学习视频任务已经完成，可以参加考试啦！',
                    icon: 'none',
                    duration: 3000
                  })
                  wx.switchTab({
                    url: '/pages/tiku/fenlei',
                  })
                }  
            }
        }).catch(e => {
            wx.showModal({
            title: e
            })
        })
      }else{
        wx.reLaunch({
          url: '/pages/user/bind/index',
        });
      }
    } catch (e) {
      wx.reLaunch({
        url: '/pages/user/bind/index',
      });
    }
  },
  //暂停
  pause: function (e) {
    //var that = this;
    //console.log('暂停按钮被调用')
    is_play = 0;
    var endtime = Date.parse(new Date());
    //console.log('视频暂停时间:'+endtime)
    // 相差的毫秒数
    const msec = endtime - starttime;
    const msec1 = msec/1000;
    //console.log('视频暂停时长msec1:'+msec1) 
    //console.log('视频暂停播放进度:'+this.data.video_real_time)
    var id = e.currentTarget.dataset.item.id;
   // console.log('暂停组件中id:'+id)
    var learnVideoTaskId = e.currentTarget.dataset.item.learnVideoTaskId;
   // console.log('暂停组件中learnVideoTaskId:'+learnVideoTaskId)
    var sort = e.currentTarget.dataset.item.sort;
    //console.log('暂停组件中sort:'+sort)
    var isEnd = e.currentTarget.dataset.item.isEnd;
    //console.log('暂停组件中isEnd:'+isEnd)1
    try {
      var empinfo = wx.getStorageSync('empinfo');
      if (empinfo) {
        //console.log('进入播放暂停后台')
            app.formPost('/wx/video/video_pause', {
              'employeeId': empinfo.employeeId,
              'learnVideoTaskId': learnVideoTaskId,
              'id':id,
              'isEnd': isEnd,
              'playLength': msec1,
              'startDate':starttime,
              'sort': sort,
              'video_real_time': this.data.video_real_time
          }).then(res => {
              if (res.code == 200) {
                console.log('视频暂停播放')
              }
          }).catch(e => {
              wx.showModal({
              title: e
              })
          })
      }else{
        wx.reLaunch({
          url: '/pages/user/bind/index',
        });
      }
    } catch (e) {
      wx.reLaunch({
        url: '/pages/user/bind/index',
      });
    }
  },
  identityCheckTime: function(videoDuration){
    if(videoDuration <= 600){
			identityCheckTime1 = Math.ceil(videoDuration/2);
		}else if(videoDuration > 600 && videoDuration <= 1200){
			identityCheckTime1 = 300;
			identityCheckTime2 = 600+Math.ceil((videoDuration-600)/2);
		}else if(videoDuration > 1200 && videoDuration<= 1800){
			identityCheckTime1 = 300;
			identityCheckTime2 = 900;
			identityCheckTime3 = 1200+Math.ceil((videoDuration-1200)/2);
		}else if(videoDuration > 1800 && videoDuration <= 2400){
			identityCheckTime1 = 300;
			identityCheckTime2 = 900;
			identityCheckTime3 = 1500;
			identityCheckTime4 = 1800+Math.ceil((videoDuration-1800)/2);
		}else if(videoDuration > 2400 && videoDuration <= 3000){
			identityCheckTime1 = 300;
			identityCheckTime2 = 900;
			identityCheckTime3 = 1500;
			identityCheckTime4 = 2100;
			identityCheckTime5 = 2400+Math.ceil((videoDuration-2400)/2);
		}else if(b > 3000 && b <= 3600){
			identityCheckTime1 = 300;
			identityCheckTime2 = 900;
			identityCheckTime3 = 1500;
			identityCheckTime4 = 2100;
			identityCheckTime5 = 2700;
			identityCheckTime6 = 3000+Math.ceil((videoDuration-3000)/2);
    }
  },
  waiting: function (e) {
    //console.log('视频缓冲')
    //console.log(e)
  },
  error: function (e) {
    //console.log('视频播放出错时')
    console.log(e)
  },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
      is_play = 0
     // console.log('onReady')
      //var admins = wx.getStorageSync('admins');
      
      //console.log('onReady'+is_play)
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      //console.log('onShow'+is_play)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
      //console.log('onHide'+is_play)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        //console.log('onUnload====='+is_play)
        if(is_play == 1){
          //console.log('onUnload====='+onUnload_TaskId)
          //console.log('onUnload====='+onUnload_id)
          //console.log('onUnload====='+onUnload_isEnd)
          //console.log('onUnload====='+onUnload_sort)
          var endtime = Date.parse(new Date());
          //console.log('视频暂停时间:'+endtime)
          // 相差的毫秒数
          const msec = endtime - starttime;
          const msec1 = msec/1000;
          //console.log('视频返回时时长==:'+msec1)
          try {
            var empinfo = wx.getStorageSync('empinfo');
            if (empinfo) {
              //console.log('进入播放暂停后台')
                  app.formPost('/wx/video/video_pause', {
                    'employeeId': empinfo.employeeId,
                    'learnVideoTaskId': onUnload_TaskId,
                    'id':onUnload_id,
                    'isEnd': onUnload_isEnd,
                    'playLength': msec1,
                    'startDate':starttime,
                    'sort': onUnload_sort,
                    'video_real_time': this.data.video_real_time
                  }).then(res => {
                      if (res.code == 200) {
                        console.log('视频暂停播放')
                      }
                  }).catch(e => {
                      wx.showModal({
                      title: e
                      })
                  })
              }else{
                wx.reLaunch({
                  url: '/pages/user/bind/index',
                });
              }
            } catch (e) {
              wx.reLaunch({
                url: '/pages/user/bind/index',
              });
            }
          // var videoCtx = wx.createVideoContext("myVideo", this);
          // videoCtx.pause();
        }
    },
    // 身份校验 获取用户输入的内容
  getUserInput(event) {
    const identityCheckContent = event.detail.value || event.detail.text;
    //console.log('验证输入内容1为：'+identityCheckContent )
    this.setData({identityCheckContent: identityCheckContent})
  },
 
  // 身份校验取消按钮触发事件
  cancelSelected(event) {
    console.log('验证取消' )
  },
 
  //  身份校验确定按钮触发事件
  successSelected(event) {
    var name = this.data.identityCheckContent;
    var employeeName1 = this.data.employeeName;
    var identityCheckTime1 = this.data.identityCheckTime;
    if(name != employeeName1){
      
      //插入验证表
      try {
        var empinfo = wx.getStorageSync('empinfo');
        if (empinfo) {
          //console.log('进入播放暂停后台')
              app.formPost('/wx/video/insert_identity_check_record', {
                'employeeId': empinfo.employeeId,
                'learnVideoTaskId': learn_video_task_id,
                'learnVideoId':learn_video_id,
                'audioDuration': videoDuration,
                'checkContent': name,
                'status':0
              }).then(res => {
                  if (res.code == 200) {
                    wx.showToast({
                      title: '与登录用户姓名不一致，请重新输入',
                      icon: 'none',
                      duration: 3000
                    })
                  }
              }).catch(e => {
                  wx.showModal({
                  title: e
                  })
              })
          }else{
            wx.reLaunch({
              url: '/pages/user/bind/index',
            });
          }
        } catch (e) {
          wx.reLaunch({
            url: '/pages/user/bind/index',
          });
        }
    }else{
      this.setData({completed: false});
      //插入验证表--待完善
      //插入验证表
      try {
        var empinfo = wx.getStorageSync('empinfo');
        if (empinfo) {
          //console.log('进入播放暂停后台')
              app.formPost('/wx/video/insert_identity_check_record', {
                'employeeId': empinfo.employeeId,
                'learnVideoTaskId': learn_video_task_id,
                'learnVideoId':learn_video_id,
                'audioDuration': videoDuration,
                'checkContent': name,
                'status':1
              }).then(res => {
                  if (res.code == 200) {
                    this.setData({
                      initial_time: identityCheckTime1+1,
                      completed: false
                    })
                    var videoCtx = wx.createVideoContext("myVideo", this);
                    videoCtx.seek(identityCheckTime1+1);
                    videoCtx.play();
                  }
              }).catch(e => {
                  wx.showModal({
                  title: e
                  })
              })
          }else{
            wx.reLaunch({
              url: '/pages/user/bind/index',
            });
          }
        } catch (e) {
          wx.reLaunch({
            url: '/pages/user/bind/index',
          });
        }
    }
    
  },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})